package com.test.admin.service.impl;

import com.test.admin.dao.ScriptDAO;
import com.test.admin.pojo.Script;
import com.test.admin.quartz.QuartzManager;
import com.test.admin.quartz.ScriptStatus;
import com.test.admin.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
public class ScriptServiceImpl implements ScriptService {
    private String JOB_GROUP = "g1";
    private String TRIGGER_GROUP = "g1";
    @Autowired
    private ScriptDAO scriptDAO;

    @PostConstruct //初始化完成之后运行
    private void init() {
        Script criteria = new Script();
        criteria.setStatus(ScriptStatus.RUNNING);
        List<Script> scripts = scriptDAO.getScriptList(criteria);
        for (Script script : scripts) {
            try {
                Class jobClass = Class.forName(script.getName());
                QuartzManager.addJob(script.getName(), JOB_GROUP, script.getName(), TRIGGER_GROUP, jobClass, script.getCron());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void addScript(Script script) {
        script.setStatus(ScriptStatus.NOT_RUN);
        scriptDAO.addScript(script);
    }

    @Override
    public void updateScript(Script script) {
        scriptDAO.updateScript(script);
    }

    @Override
    public List<Script> getScriptList(Script script) {
        return scriptDAO.getScriptList(script);
    }

    @Override
    public void doResumeJob(Integer id) {
        Script script = scriptDAO.getScriptById(id);
        try {
            int status = QuartzManager.getJobStatus(script.getName(), TRIGGER_GROUP);
            if (status == 2) {//Quartz中2是暂停  0删除
                QuartzManager.resumeJob(script.getName(), TRIGGER_GROUP);
            } else {//比如在恢复脚本之前，重启过系统，Quartz中没有这个任务
                Class jobClass = Class.forName(script.getName());
                QuartzManager.addJob(script.getName(), JOB_GROUP, script.getName(), TRIGGER_GROUP, jobClass, script.getCron());
            }
            script.setStatus(ScriptStatus.RUNNING);
            scriptDAO.updateScript(script);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doPauseJob(Integer id) {
        Script script = scriptDAO.getScriptById(id);
        QuartzManager.pauseJob(script.getName(), JOB_GROUP);
        script.setStatus(ScriptStatus.PAUSE);
        scriptDAO.updateScript(script);
    }
}
